import {
	HTTP_REQUEST_URL,
	HEADER,
	TOKENNAME,
	TIMEOUT
} from '@/config/app';
import $store from '@/store/index'

/**
 * 发送请求
 */
function baseRequest(url, method, data, {
	noAuth = false,
	noVerify = false
}) {
	let Url = '';
	if (url.includes('/index.php')) {
		Url = 'https://api.f4.huoke999.com'
	} else {
		Url = HTTP_REQUEST_URL
	}
	console.log(Url);
	let header = {
		...HEADER
	};
	// 动态获取最新的token
	if (!noAuth) {
		const token = $store.getters.token || uni.getStorageSync('token') || '';
		if (token) {
			header['Authorization'] = token;
		}
	}

	uni.showToast({
		icon: 'loading',
        title:'数据请求中...'
	})

	return new Promise((reslove, reject) => {
		if (uni.getStorageSync('locale')) {
			// header['Cb-lang'] = uni.getStorageSync('locale') // 删除解决跨域(临时)
		}

		uni.request({
			url: Url + url,
			method: method || 'GET',
			header: header,
			data: data || {},
			timeout: TIMEOUT,
			success: (res) => {
				uni.hideToast();
				if (res.data.status == 419 || res.data.status == 420 || res.data.status == 401 ||
					res.data.status == 421) {
					$store.dispatch('logout')
                    uni.reLaunch({
                    	url: '/pages/login/login'
                    })
				}
				reslove(res.data)
			},
			fail: (msg) => {
				reject(msg)
			}
		})
	});
}

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, opt) => baseRequest(api, method, data, opt || {})
});



export default request;